package service

import (
	"gorm.io/gorm"
	"guns-go/global"
	"guns-go/model"
	"guns-go/model/request"
	"strconv"
	"strings"
)

func GetRoleMenuIdList(roleIds []int) (err error, menuIds []int) {

	var roleMenus []model.SysRoleMenu
	err = global.GVA_DB.Where("role_id in (?)", roleIds).Find(&roleMenus).Error

	if err != nil {
		return err, nil
	}

	if len(roleMenus) > 0 {
		menuIds = make([]int, 0)
		for _, roleMenu := range roleMenus {
			menuIds = append(menuIds, roleMenu.MenuId)
		}
		return err, menuIds
	}

	return err, nil
}

func SaveRoleMenu(roleMenu *model.SysRoleMenu, tx *gorm.DB) error {
	return tx.Create(roleMenu).Error
}

func deleteRoleMenuListByMenuIdList(menuIdSlice []int, tx *gorm.DB) error {
	return tx.Delete(model.SysRoleMenu{}, "menu_id in(?)", menuIdSlice).Error
}

func DeleteRoleMenuListByRoleId(roleId int, tx *gorm.DB) error {
	return tx.Delete(model.SysRoleMenu{}, "role_id = ?", roleId).Error
}

func RoleMenuGrantMenu(sysRoleParam *request.SysRoleParam, tx *gorm.DB) error {

	roleId := sysRoleParam.Id

	//删除所拥有菜单
	err := DeleteRoleMenuListByRoleId(roleId, tx)

	if err != nil {
		return err
	}

	//授权菜单
	if len(sysRoleParam.GrantMenuIdList) > 0 {

		//casbin
		casbinInfos := make([]request.CasbinInfo, 0)

		for _, menuId := range sysRoleParam.GrantMenuIdList {
			roleMenu := new(model.SysRoleMenu)
			roleMenu.RoleId = roleId
			id, _ := strconv.Atoi(menuId)
			roleMenu.MenuId = id

			err = SaveRoleMenu(roleMenu, tx)

			if err != nil {
				return err
			}

			//查询菜单标示
			err, sysMenu := QuerySysMenuById(&id)

			if err != nil {
				return err
			}

			if sysMenu.Permission != "" {
				permission := ":" + sysMenu.Permission
				url := strings.ReplaceAll(permission, global.COLON, global.LeftDivide)

				casbinInfo := request.CasbinInfo{
					Path:   url,
					Method: sysMenu.Method,
				}
				casbinInfos = append(casbinInfos, casbinInfo)
			}
		}

		//TODO 更新casbin
		err = UpdateCasbin(strconv.Itoa(roleId), casbinInfos)

		if err != nil {
			return err
		}
	}

	return nil
}
